package com.troila.cloud.simplify.filter;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.troila.cloud.simplify.model.SAnswer;

public class SessionFilter implements Filter {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SessionFilter.class);

    @Value("$(serverurl)")
    private String serverurl;
    /**
     * 封装，不需要过滤的list列表
     */
    protected static List<Pattern> patterns = new ArrayList<Pattern>();
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    	
        patterns.add(Pattern.compile("front/regist"));
        patterns.add(Pattern.compile("front/access"));
        patterns.add(Pattern.compile("front/index"));
        patterns.add(Pattern.compile("front/login"));
        patterns.add(Pattern.compile("front/forgetPsd"));
        patterns.add(Pattern.compile("front/home"));
        patterns.add(Pattern.compile("api/product/frontList"));
        patterns.add(Pattern.compile("api/getMsgCode"));
        patterns.add(Pattern.compile("api/checkUserId"));
        patterns.add(Pattern.compile("api/register"));
        patterns.add(Pattern.compile("api/forgetPsd"));
        patterns.add(Pattern.compile("api/redisSet"));
        patterns.add(Pattern.compile("api/redisSetTime"));
        patterns.add(Pattern.compile("api/redisGet"));
        patterns.add(Pattern.compile("back/login"));
        patterns.add(Pattern.compile("api/product/getProductDiscount"));
        patterns.add(Pattern.compile("api/user/synUserInfo"));
        patterns.add(Pattern.compile("api/user/platformCheckToken"));
        
        patterns.add(Pattern.compile("main/post.*"));
        patterns.add(Pattern.compile(".*[(\\.js)||(\\.css)||(\\.png)||(\\.doc)||(\\.pdf)]"));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
        if (url.startsWith("/") && url.length() > 1) {
            url = url.substring(1);
        }
        if (isInclude(url)){
            chain.doFilter(httpRequest, httpResponse);
            return;
        } else {
            HttpSession session = httpRequest.getSession();
            if (session.getAttribute("userId") != null){
                // session存在
            	SAnswer user = (SAnswer) session.getAttribute("user");
//            	String ifAdmin = user.getIfAdmin();
            	//不是管理员
//            	if("0".equals(ifAdmin)) {
//            		if(url.startsWith("back")) {
//            			httpResponse.sendRedirect("/front/index");
//            		}	
//            	}
            	//是管理员
//            	else if("1".equals(ifAdmin)) {
//            		if(url.startsWith("front")) {
//            			httpResponse.sendRedirect("/back/login");
//            		}
//            	}
                chain.doFilter(httpRequest, httpResponse);
                return;
            } else {
                // session不存在 准备跳转失败
            	if(url.startsWith("back")) {
            		httpResponse.sendRedirect("/back/login");
            	}else if(url.startsWith("/")) {
            		httpResponse.sendRedirect("/front/index");
            	}
            	else {
            		httpResponse.sendRedirect("/front/login");
            	}
                
            }
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * 是否需要过滤
     * @param url
     * @return
     */
    private boolean isInclude(String url) {
        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }

}